package com.z_talk.server.core;

import com.z_talk.server.config.PropertiesUtil;
import com.z_talk.server.view.ServerView;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

import javax.swing.*;

public class ServerMain {

    public static ServerView serverView;

    public static void main(String[] args) throws InterruptedException {
        int port = Integer.parseInt(PropertiesUtil.configProp.getProperty("port"));
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,1024).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast("decoder",new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
                    pipeline.addLast("encoder",new ObjectEncoder());
                    pipeline.addLast(new ServerHandler());
                }
            });
            System.out.println("Netty server start ...");
            ChannelFuture cf = bootstrap.bind(port).sync();

            cf.addListener(cd->{
                if(cd.isSuccess()){
                    System.out.println("success");
                }else{
                    System.out.println("failed");
                }
            });
            JFrame.setDefaultLookAndFeelDecorated(true);
            JDialog.setDefaultLookAndFeelDecorated(true);
            serverView = new ServerView();
            cf.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }



}
